import React, { useState } from 'react';
import {
  Card,
  Table,
  Tag,
  Button,
  Typography,
  Modal,
  Descriptions,
  message,
  Select,
  Form
} from 'antd';
import {
  ToolOutlined,
  ExclamationCircleOutlined,
  UserOutlined,
  WalletOutlined,
  ContainerOutlined
} from '@ant-design/icons';

const { Title, Paragraph } = Typography;
const { Option } = Select;

const mockFailedTrades = [
  {
    key: '1',
    clientId: 'CUST-007',
    clientName: '王先生',
    portfolioName: '稳健增长FOF组合',
    failedFund: '华夏成长混合',
    tradeType: '卖出',
    amount: '5,000.00元',
    reason: '基金状态禁止赎回',
    status: 'unprocessed'
  },
  {
    key: '2',
    clientId: 'CUST-042',
    clientName: '李女士',
    portfolioName: '稳健增长FOF组合',
    failedFund: '易方达消费行业',
    tradeType: '买入',
    amount: '8,000.00元',
    reason: '客户账户余额不足',
    status: 'unprocessed'
  },
  {
    key: '3',
    clientId: 'CUST-113',
    clientName: '赵先生',
    portfolioName: '大类资产轮动',
    failedFund: '广发纳斯达克100ETF',
    tradeType: '买入',
    amount: '12,000.00元',
    reason: '交易触发风控限制',
    status: 'unprocessed'
  }
];

const mockAlternativeFunds = {
    '华夏成长混合': ['嘉实新兴产业股票', '景顺长城鼎益混合(LOF)'],
    '易方达消费行业': ['汇添富消费行业混合', '中欧消费主题股票'],
    '广发纳斯达克100ETF': ['国泰纳斯达克100ETF', '华安纳斯达克100ETF'],
};

const STORAGE_KEY = 'errorHandlingFailedTrades';

const ErrorHandling = () => {
  const local = localStorage.getItem(STORAGE_KEY);
  const [failedTrades, setFailedTrades] = useState(local ? JSON.parse(local) : mockFailedTrades);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedTrade, setSelectedTrade] = useState(null);
  const [form] = Form.useForm();

  const handleOpenModal = (record) => {
    setSelectedTrade(record);
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  const handleResubmit = (values) => {
    message.loading({ content: '正在生成新的交易指令...', key: 'resubmit' });
    
    setTimeout(() => {
      console.log('Resubmitting with:', values);
      message.success({ content: '替代交易指令已成功下发！', key: 'resubmit', duration: 2 });
      setIsModalVisible(false);
      // Remove the processed trade from the list
      const newTrades = failedTrades.filter(trade => trade.key !== selectedTrade.key);
      setFailedTrades(newTrades);
      localStorage.setItem(STORAGE_KEY, JSON.stringify(newTrades));
      form.resetFields();
    }, 1500);
  };

  const columns = [
    { title: '客户姓名', dataIndex: 'clientName', key: 'clientName' },
    { title: '客户账号', dataIndex: 'clientId', key: 'clientId' },
    { title: '关联组合', dataIndex: 'portfolioName', key: 'portfolioName' },
    { title: '失败标的', dataIndex: 'failedFund', key: 'failedFund' },
    { title: '失败原因', dataIndex: 'reason', key: 'reason', render: reason => <Tag color="error">{reason}</Tag> },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button
          type="primary"
          danger
          icon={<ToolOutlined />}
          onClick={() => handleOpenModal(record)}
        >
          处理
        </Button>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Title level={3}>交易差错处理</Title>
      <Paragraph type="secondary">
        处理因客户账户、基金状态等原因导致的失败交易单，可为客户替换为同类标的并重新下发交易指令。
      </Paragraph>

      <Card>
        <Table
          dataSource={failedTrades}
          columns={columns}
          rowKey="key"
          pagination={{ pageSize: 5 }}
        />
      </Card>

      <Modal
        title={
            <div style={{display: 'flex', alignItems: 'center'}}>
                <ExclamationCircleOutlined style={{marginRight: 8, color: 'red'}}/>
                <span>处理失败交易</span>
            </div>
        }
        open={isModalVisible}
        onCancel={handleCancel}
        footer={null} // Use custom footer in Form
      >
        {selectedTrade && (
          <>
            <Descriptions bordered size="small" column={1} style={{ marginBottom: 24 }}>
              <Descriptions.Item label={<><UserOutlined/> 客户信息</>}>{selectedTrade.clientName} ({selectedTrade.clientId})</Descriptions.Item>
              <Descriptions.Item label={<><ContainerOutlined/> 关联组合</>}>{selectedTrade.portfolioName}</Descriptions.Item>
              <Descriptions.Item label={<><WalletOutlined/> 失败标的</>}>{selectedTrade.failedFund}</Descriptions.Item>
              <Descriptions.Item label="交易类型">{selectedTrade.tradeType}</Descriptions.Item>
              <Descriptions.Item label="交易金额">{selectedTrade.amount}</Descriptions.Item>
              <Descriptions.Item label="失败原因"><Tag color="error">{selectedTrade.reason}</Tag></Descriptions.Item>
            </Descriptions>

            <Form form={form} layout="vertical" onFinish={handleResubmit}>
              <Form.Item
                name="replacementFund"
                label="选择替代标的"
                rules={[{ required: true, message: '请选择一个替代基金' }]}
              >
                <Select placeholder="请选择同类基金进行替换">
                  {mockAlternativeFunds[selectedTrade.failedFund]?.map(fund => (
                    <Option key={fund} value={fund}>{fund}</Option>
                  ))}
                </Select>
              </Form.Item>
              
              <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
                <Button onClick={handleCancel} style={{ marginRight: 8 }}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  重新下发指令
                </Button>
              </Form.Item>
            </Form>
          </>
        )}
      </Modal>
    </div>
  );
};

export default ErrorHandling; 